package com.ai.trickycards

import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import com.ai.trickycards.entity.UserInfo
import com.ai.trickycards.entity.enumeration.LevelRangeEnum
import com.ai.trickycards.utils.SP
import com.google.gson.Gson
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch

class AppViewModel(val app: Application) : AndroidViewModel(app) {

    private val gson = Gson()

    private val initUserInfo by lazy {
        SP.getString(app, Constant.SP_KEY.USER_INFO)?.let { userJson ->
            gson.fromJson(userJson, UserInfo::class.java)
        } ?: UserInfo(
            headIcon = listOf(
                R.mipmap.head01,
                R.mipmap.head02,
                R.mipmap.head03,
                R.mipmap.head04
            ).shuffled().first(),

            // 初级积分默认为1000，完成等级后默认积分会相应提升，提升细则见等级成就
            //score = LevelRangeEnum.P1.levelScore
        )

    }

    private val _userInfoFlow = MutableStateFlow(initUserInfo)
    val userInfoFlow = _userInfoFlow.asStateFlow()

    fun changeUserInfo(userInfo: UserInfo) = viewModelScope.launch {
        userInfo.changeTimeMillis = System.currentTimeMillis()
        saveUserInfo(userInfo)
        _userInfoFlow.emit(userInfo)
    }

    private fun saveUserInfo(userInfo: UserInfo) {
        SP.putString(app, Constant.SP_KEY.USER_INFO, gson.toJson(userInfo))
    }

}